package org.grayrabbit.cms.plugin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.dom4j.Element;
import org.grayrabbit.cms.plugin.elements.ResourceDescriptor;
import org.grayrabbit.cms.plugin.elements.ResourceLocation;


public class Resources implements Resourced {
	public static final  List<ResourceDescriptor> EMPTY_RESOURCEDESCRIPTORS = Collections.emptyList();
	public static final Resources EMPTY_RESOURCES = new Resources(EMPTY_RESOURCEDESCRIPTORS);
	private List<ResourceDescriptor> resourceDescriptors;

	public static Resources fromXml(Element element)
			throws PluginParseException, IllegalArgumentException {
		if (element == null) {
			throw new IllegalArgumentException("Cannot parse resources from null XML element");
		}
		@SuppressWarnings("unchecked")
		List<Element> elements = element.elements("resource");
		List<ResourceDescriptor> templates = new ArrayList<ResourceDescriptor>(elements.size());

		for (Element el : elements) {
			ResourceDescriptor resourceDescriptor = new ResourceDescriptor(el);
			if (templates.contains(resourceDescriptor)) {
				throw new PluginParseException("Duplicate resource with type '"
						+ resourceDescriptor.getType() + "' and name '"
						+ resourceDescriptor.getName() + "' found");
			}
			templates.add(resourceDescriptor);
		}
		return new Resources(templates);
	}

	  public Resources(List<ResourceDescriptor> resourceDescriptors) throws IllegalArgumentException
	  {
	    if (resourceDescriptors == null)
	      throw new IllegalArgumentException("Resources cannot be created with a null resources list. Pass empty list instead");
	    this.resourceDescriptors = resourceDescriptors;
	  }

	  public List<ResourceDescriptor> getResourceDescriptors()
	  {
	    return this.resourceDescriptors;
	  }

	  public List<ResourceDescriptor> getResourceDescriptors(String type)
	  {
		  List<ResourceDescriptor> typedResourceDescriptors = new LinkedList<ResourceDescriptor>();
		  for (ResourceDescriptor resourceDescriptor: resourceDescriptors)
		    {
			      if (resourceDescriptor.getType().equalsIgnoreCase(type))
			      {
			    	  typedResourceDescriptors.add(resourceDescriptor);
			      }
		    }
		    return typedResourceDescriptors;
	  }

	public ResourceLocation getResourceLocation(String type, String name) {
		for (ResourceDescriptor resourceDescriptor : resourceDescriptors) {
			if (resourceDescriptor.doesTypeAndNameMatch(type, name)) {
				return resourceDescriptor.getResourceLocationForName(name);
			}
		}

		return null;
	}
}
